<template>
  <n-modal v-model:show="isVisible" title="添加产品" preset="dialog" @close="onClose" @update:show="onClose" style="height: 650px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <!-- 第一行：产品名称 和品牌-->
      <div class="form-row">
        <n-form-item label="产品名称：" path="name">
          <n-input v-model:value="form.name" placeholder="请输入产品名称" />
        </n-form-item>
        <n-form-item label="产品品牌">
          <n-select v-model:value="form.brandId"
                    :options="brands"
                    placeholder="请选择品牌"
                    style="width: 150px"></n-select>
        </n-form-item>
          <n-form-item label="产品分类：" path="category">
              <n-cascader
                      v-model:value="form.categoryId"
                      style="width:160px"
                      :options="option"
                      filterable
              >
              </n-cascader>
          </n-form-item>
      </div>
      <!-- 第二行：产品分类和产品属性 -->
      <div class="form-row">
        <n-form-item label="产品属性：" path="attributes">
          <n-select v-model:value="form.attributeId" :options="attributes" placeholder="选择产品属性" filterable />
        </n-form-item>
          <n-form-item label="产品状态：" path="type">
              <n-select v-model:value="form.status"
                        :options="statusOptions"
                        placeholder="请选择产品状态"
                        style="width: 150px"></n-select>
          </n-form-item>
          <n-form-item label="供应商：" path="supplier">
              <n-select v-model:value="form.supplierId" :options="suppliers" placeholder="选择供应商" filterable />
          </n-form-item>
      </div>
      <!-- 第三行：产品类型、供应商、状态 -->
      <div class="form-row">
          <n-form-item label="成本：" path="cost">
              <n-input-number v-model:value="form.cost" placeholder="请输入成本" />
          </n-form-item>
      </div>
        <span>上传图片(默认第一张图作为产品首图)</span>
        <n-upload
                action="#"
                list-type="image-card"
                :max="5"
                multiple
                @before-upload="beforeUpload"
                accept="image"
                @remove="handleRemove"
                :default-upload="false"
        />
      <!-- 提交按钮 -->
        <div class="submit-row">
            <n-form-item label="产品文案：" path="type">
                <n-input
                        v-model:value="form.type"
                        type="textarea"
                        placeholder=""
                        maxlength="500"
                        style="width: 660px;"
                        :autosize="{
                                minRows: 5,
                                maxRows: 8
                              }"
                        show-count
                />
            </n-form-item>
        </div>
      <div class="submit-row">
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import { useMessage } from 'naive-ui';
import api from "@/api/admin.js";
import {useRouter} from 'vue-router';
import {useUserStore} from "@/store/index.js";
import {request} from "@/utils/index.js";
let files = []
const beforeUpload = ({file}) => {
	const fileType = ["image/png", "image/jpeg", "image/jpg"]; // 通常包括image/jpeg
	if (!fileType.includes(file.file?.type)) {
		// 如果文件类型不在允许的列表中，显示错误消息并返回false
		$message.error("只能上传png或jpg格式的图片文件，请重新上传");
		return false;
	}
	files.push(file)
	return true;
}
const	imageList =[]
const handleRemove = ({index}) => {
	files = files.filter((_, i) => i !== index);
}
const customRequest = async (file) => {
	try{
		const formData = new FormData();
		formData.append("file", file.file)
		const res = await api.uploadFile(formData)
		if(res.code === 200) {
			imageList.push(res.data)
		}
		else {
			$message.error(res.message)
		}
  }catch (e) {
    $message.error("图片上传失败！")
	}
}
const brands=ref([])
const attributes=ref([])
const range = ref(null)
const userStore = useUserStore()
const loading = ref(false)
const id = userStore.getId();
const router = useRouter()
const emit = defineEmits(['updatePage'])
const props = defineProps({
  show: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
});
const option = ref([
  {
    label:'全部',
    value:-1
  }
])
const isVisible = ref(props.show);
watch(() => props.show, (newVal) => {
  isVisible.value = newVal;
});

const form = ref({
  name: '',
  categoryId: null,
  attributesId: null,
  type: '',
  supplierId: null,
  status: null,
  cost: null,
  brandId:'',
	picture:""
});
const uploadImage = async () => {
	try {
		// 使用 Promise.all 等待所有 customRequest 调用完成
		await Promise.all(files.map((file) => customRequest(file)));
		// 现在所有的文件都已经上传完成，可以安全地打印 imageList 的长度
    form.value.picture = imageList.join(",")
    console.log(form.value.picture)
	} catch (err) {
		$message.error("添加产品失败！");
	}
}
const handleSubmit = async () => {
  try {
		await uploadImage()
    const res = await api.addProduct(
      {
        ...form.value,
        score:0,
      }
    )
    if(res.code === 200) {
      emit("updatePage")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("添加产品失败！")
  }finally{
    clear()
    props.onClose();
  }
};
const clear = () => {
	form.value = {
		name: '',
		categoryId: null,
		attributesId: null,
		type: '',
		supplierId: null,
		status: null,
		cost: null,
		brandId: '',
		photo: []
	};
}
const queryAllProductCategory = async  () => {
  try {
    const res = await api.findAllProductCategory()
    if(res.code === 200) {
      // 调用函数生成n-cascader的options
      convertToCascaderOptions(res.data);
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品失败！")
  }finally{
    loading.value = false
  }
}
const convertToCascaderOptions = (flatData) => {
  const idNodeMap = {}; // 用于映射id到对应的节点对象
  const opt = []; // 最终生成的级联选择器数据
  // 首先，将所有的数据节点放到一个映射表中，方便后续通过ID快速查找
  flatData.forEach(node => {
    idNodeMap[node.id] = { ...node, children: [] };
  });
  // 构建树形结构
  Object.values(idNodeMap).forEach(node => {
    if (node.parentCategoryId === null) {
      // 如果parentId为null，则该节点是根节点
      opt.push(node);
    } else {
      // 否则，将该节点添加到其父节点的children数组中
      const parentNode = idNodeMap[node.parentCategoryId];
      if (parentNode) {
        parentNode.children.push(node);
      }
    }
  });
  console.log(opt)
  // 遍历并转换所有根节点
  option.value = opt.map(node=>{
    return traverse(node)
  });
}
// 转换数据结构为n-cascader所接受的格式（将name和parentName转换为label，并移除不必要的字段）
const traverse = (node) => {
  const { id, name, children } = node;
  // 如果children数组为空，则不返回children字段
  const processedNode = {
    value: id.toString(),
    label: name,
    ...(children.length > 0 ? { children: children.map(child => traverse(child)) } : {})
  };
  return processedNode;
};
const queryBrandList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProductBrand()
    if(res.code === 200) {
      res.data.map((item)=>{
        brands.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const statusOptions = [
  { label: '开发中', value: '开发中' },
  { label: '在售', value: '在售' },
	{ label: '下架', value: '下架' },
];
const suppliers=ref([])
const querySupplierList = async () => {
  loading.value = true
  try {
    const res = await api.findAllSupplier()
    if(res.code === 200) {
      res.data.map((item)=>{
        suppliers.value.push({
          label: item.name,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  }finally{
    loading.value = false
  }
}
const queryAttributeList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProductAttribute()
    if(res.code === 200) {
      res.data.map((item)=>{
        const specification = item.specification != null ? item.specification.toString() : 'null';
        const color = item.color != null ? item.color.toString() : 'null';
        const material = item.material != null ? item.material.toString() : 'null';
        const all = specification +"/"+ color +"/"+ material;
        console.log(all);
        attributes.value.push({
          label: all,
          value: item.id
        })
      })
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取属性信息失败！")
  }finally{
    loading.value = false
  }
}
const rowKey = (rowData) => {
  return rowData.id
}
onMounted(()=>{
  querySupplierList()
  queryAllProductCategory()
  queryAttributeList()
  queryBrandList()
})
</script>

<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
  position: relative;
}

.image-upload {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 150px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-placeholder {
  color: #999;
  font-size: 14px;
  text-align: center;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.form-row {
  display: flex;
  gap: 20px;
  align-items: center;
  width: 100%;
}

.form-row > n-form-item {
  flex: 1;
}

.submit-row {
  justify-content: center;
  display: flex;
  width: 100%;
}
</style>
